package q200;

/**
 * 200. 岛屿的数量
 */
public class Solution {

    public int numIslands(char[][] grid) {
        int landsNum = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (judge(grid, i, j)) {
                    landsNum += 1;
                    dfsMark(grid, i, j);
                }
            }
        }

        return landsNum;
    }

    public void dfsMark (char[][] grid, int i, int j) {
        if (!judge(grid, i, j)) return;
        grid[i][j] = '2';
        dfsMark(grid, i - 1, j);
        dfsMark(grid, i + 1, j);
        dfsMark(grid, i, j - 1);
        dfsMark(grid, i, j + 1);
    }

    public boolean judge(char[][] grid, int i, int j) {
        return i < grid.length && i >= 0 && j < grid[0].length && j >= 0 && grid[i][j] == '1';
    }
}
